package com.xjc.infra.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
/**
 * 在java 类中拼接sql
 * @author liangcz
 * @Time：2017年6月2日 下午4:49:26
 * @version 1.0
 */
public class SqlFormatUtil {
	/**
	 * 读取sql
	 * @author liangcz
	 * @date   2017年6月2日 下午4:52:53
	 * @return String
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public List<String> readSql() throws FileNotFoundException, IOException{
		String basePath = new File(".").getAbsolutePath();
		String fileName = "/src/main/java/com/xjc/infra/util/sql.txt";
		File file = new File(basePath + fileName);
		List<String> lines = IOUtils.readLines(new FileInputStream(file));
		return lines;
	}
	/**
	 * 格式化成java需要的sql
	 * @author liangcz
	 * @date   2017年6月2日 下午4:56:58
	 * @return String
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public String format() throws FileNotFoundException, IOException{
		List<String> lines = readSql();
		String changeLine = "\n";
		String space = " ";
		String spaceT = "\t";
		String quotes = "\"";
		String plus = "+";
		String sql = "" ;
		int c = 1;
		for (String line : lines) {
			if(c++ == 1){
				sql = "String sqlstr = " + quotes + line + space + quotes;
			}else{
				sql = sql + changeLine + spaceT + space + space + space + plus + space + quotes + space + line + space + quotes;
			}
		}
		sql += ";";
		System.out.println("sql[\n" + sql + "");
		System.out.println("Sql sql = Sqls.create(sqlstr);\n");
		System.out.println("]\n");
		return sql;
	}
	/**
	 * 把sql保存到sql.txt,运行测试，生成指定的sql
	 * @author liangcz
	 * @date   2017年6月2日 下午6:27:37
	 * @return void
	 */
	@Test
	public void test_format() throws FileNotFoundException, IOException{
		format();
	}
	/**
	 * 打印出原来的sql
	 * @author liangcz
	 * @date   2017年7月11日 下午5:52:25
	 * @return void
	 */
	@Test
	public void test_deformat(){
		String sqlstr = "SELECT a.* "
				   + "   FROM cms_contract_mast a, srv_ssq_contract_xref b "
				   + "  WHERE a.cod_contract_id = b.cod_contract_id  "
				   + "  AND a.cod_business_code = @cod_business_code and b.flg_confuse = 'n'"
				   + "  AND b.cod_contract_status = 1 ";
		sqlstr.replaceAll("[@@]", "@");
		System.out.println(sqlstr);
	}	
}